<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="公司名称：">
							<el-input v-model="transferVal1" placeholder="请输入公司名称" />
						</el-form-item>
						<el-form-item label="值班表名称：">
							<el-input v-model="transferVal2" placeholder="请输入值班表名称" />
						</el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('DutyRoster1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('DutyRoster7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="值班表名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="formName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.formName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="公司名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="companyName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.companyName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="联系人" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="empName" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.empName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="联系人电话" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="contactPhoneNumber" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.contactPhoneNumber }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新时间" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新人" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="备注" align="center">
											<template #default="scope">
												<span v-if="scope.row.remark">{{ scope.row.remark }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="180" :show-overflow-tooltip="false" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" :show-overflow-tooltip="false" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button v-if="$hasPer('DutyRoster2:create')" @click="AddedDutyPersonnelInfo(scope.row)" class="icon-e" icon="ele-Plus" size="small" text type="primary">
															值班人员
														</el-button>

														<el-button v-if="$hasPer('DutyRoster3:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>

														<el-button v-if="$hasPer('DutyRoster4:delete')" @click="deleteHandle(scope.row.n_Id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form label-width="110px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="companyName" label="公司名称">
							<el-input v-model="ruleForm.companyName" placeholder="公司名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="formName" label="值班表名称">
							<el-input v-model="ruleForm.formName" placeholder="值班表名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="contactId" label="联系人">
							<el-select filterable v-model="ruleForm.contactId" @change="selectLinkmanChange" placeholder="联系人" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="contactPhoneNumber" label="联系人电话">
							<el-input v-model="ruleForm.contactPhoneNumber" placeholder="联系人电话" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注">
							<el-input v-model="ruleForm.remark" placeholder="备注" clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 新增值班人员 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showAddNodeDialogVisible" title="值班人员信息" width="50%" @close="cancelAddNodeClick">
			<el-divider content-position="left"> 基本信息 </el-divider>
			<el-form label-width="120px" ref="watchkeeperRuleFormRef" :model="watchkeeperRuleForm" :rules="watchkeeperRules">
				<el-row :gutter="35">
					<!-- 带班领导 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="leaderId" label="值班领导">
							<!-- 下拉框请求员工列表 -->
							<el-select filterable v-model="watchkeeperRuleForm.leaderId" @change="(e) => selectLinkmanChange1(e, 'leaderContacts')" placeholder="值班领导" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="leaderPosId" label="领导岗位">
							<!-- 下拉框请求  /SMS/DutyPserson/GetPosBydEmpId ;用leaderId作为参数-->
							<!-- <el-input v-model="watchkeeperRuleForm.leaderPosId" placeholder="领导岗位" clearable /> -->
							<el-select v-model="watchkeeperRuleForm.leaderPosId" placeholder="领导岗位" style="width: 100%">
								<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="leaderContacts" label="领导电话">
							<el-input v-model="watchkeeperRuleForm.leaderContacts" placeholder="领导电话" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"></el-col>
					<!-- 值班部门负责人 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="departHeaderId" label="部门负责人">
							<!-- 员工下拉列表 -->
							<el-select filterable v-model="watchkeeperRuleForm.departHeaderId" @change="(e) => selectLinkmanChange1(e, 'departHeaderContacts')" placeholder="部门负责人" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="departHeaderPosId" label="部门负责人岗位">
							<!-- 请求/SMS/DutyPserson/GetPosBydEmpId ;用DepartHeaderId作为参数 -->
							<!-- <el-input v-model="watchkeeperRuleForm.departHeaderPosId" placeholder="部门负责人岗位" clearable /> -->
							<el-select v-model="watchkeeperRuleForm.departHeaderPosId" placeholder="部门负责人岗位" style="width: 100%">
								<el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="departHeaderContacts" label="部门负责人电话">
							<el-input v-model="watchkeeperRuleForm.departHeaderContacts" placeholder="部门负责人电话" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"></el-col>
					<!-- 值班员 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="watcherId" label="值班人">
							<!-- 员工下拉列表 -->
							<el-select filterable v-model="watchkeeperRuleForm.watcherId" @change="(e) => selectLinkmanChange1(e, 'watcherContacts')" placeholder="值班人" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="watcherContacts" label="值班室电话">
							<el-input v-model="watchkeeperRuleForm.watcherContacts" placeholder="值班室电话" clearable />
						</el-form-item>
					</el-col>
					<!-- 网络值班员 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="networkWatcherId" label="网络值班人">
							<!-- 员工下拉列表 -->
							<el-select filterable v-model="watchkeeperRuleForm.networkWatcherId" @change="(e) => selectLinkmanChange1(e, 'networkWatcherContacts')" placeholder="网络值班人" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="networkWatcherContacts" label="网络值班室电话">
							<el-input v-model="watchkeeperRuleForm.networkWatcherContacts" placeholder="网络值班室电话" clearable />
						</el-form-item>
					</el-col>
					<!-- 值班司机 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="driverId" label="司机">
							<!-- 员工下拉列表 -->
							<el-select filterable v-model="watchkeeperRuleForm.driverId" @change="(e) => selectLinkmanChange1(e, 'driverContacts')" placeholder="司机" style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="driverContacts" label="司机电话">
							<el-input v-model="watchkeeperRuleForm.driverContacts" placeholder="司机电话" clearable />
						</el-form-item>
					</el-col>
					<!-- 日期 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="dateOfDuty" label="值班日期">
							<el-date-picker style="width: 100%" v-model="watchkeeperRuleForm.dateOfDuty" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" placeholder="值班日期" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"></el-col>
					<!-- 按钮 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item>
							<el-button v-if="!editId" type="primary" @click="addDutyPerson(watchkeeperRuleFormRef)">新增</el-button>
							<el-button v-else type="primary" @click="addDutyPerson(watchkeeperRuleFormRef)">修改</el-button>
							<el-button @click="resetDutyPerson">重置</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-divider content-position="left"> 新增值班人员查看 </el-divider>
			<el-table :data="tableData" border style="width: 100%">
				<el-table-column min-width="90" :show-overflow-tooltip="true" align="center" prop="formName" label="表格名称" />
				<el-table-column min-width="90" :show-overflow-tooltip="true" align="center" :formatter="formatDate" prop="dateOfDuty" label="值班日期" />

				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" label="值班领导信息">
					<template #default="{ row }">
						<ul>
							<li style="display: flex; justify-content: start">
								<span>姓名：</span>
								<span>{{ row.leaderName }}</span>
							</li>
							<li style="display: flex; justify-content: start">
								<span>岗位：</span>
								<span>{{ row.leaderPosName }}</span>
							</li>
							<li style="display: flex; justify-content: start">
								<span>电话：</span>
								<span>{{ row.leaderContacts }}</span>
							</li>
						</ul>
					</template>
					<!-- <el-table-column min-width="140" :show-overflow-tooltip="true" align="center" prop="leaderPosName" label="值班领导岗位名称"> </el-table-column>
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" prop="leaderContacts" label="领导电话" /> -->
				</el-table-column>
				<!-- 值班部门负责人 -->
				<el-table-column min-width="130" :show-overflow-tooltip="true" align="center" label="部门负责人信息">
					<template #default="{ row }">
						<ul>
							<li style="display: flex; justify-content: start">
								<span>姓名：</span>
								<span>{{ row.departHeaderName }}</span>
							</li>
							<li style="display: flex; justify-content: start">
								<span>岗位：</span>
								<span>{{ row.departHeaderPosName }}</span>
							</li>
							<li style="display: flex; justify-content: start">
								<span>电话：</span>
								<span>{{ row.departHeaderContacts }}</span>
							</li>
						</ul>
					</template>
					<!-- <el-table-column min-width="130" :show-overflow-tooltip="true" align="center" prop="departHeaderPosName" label="部门负责人岗位"> </el-table-column>
				<el-table-column min-width="130" :show-overflow-tooltip="true" align="center" prop="departHeaderContacts" label="部门负责人电话" /> -->
				</el-table-column>
				<!-- 值班员 -->
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" label="值班人信息">
					<template #default="{ row }">
						<ul>
							<li style="display: flex; justify-content: start">
								<span>姓名：</span>
								<span>{{ row.watcherName }}</span>
							</li>
							<li style="display: flex; justify-content: start">
								<span>电话：</span>
								<span>{{ row.watcherContacts }}</span>
							</li>
						</ul>
					</template>
					<!-- <el-table-column min-width="120" :show-overflow-tooltip="true" align="center" prop="watcherContacts" label="值班室电话" /> -->
				</el-table-column>
				<!-- 网络值班 -->
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" label="网络值班人信息">
					<template #default="{ row }">
						<ul>
							<li style="display: flex; justify-content: start">
								<span>姓名：</span>
								<span>{{ row.networkWatcherName }}</span>
							</li>
							<li style="display: flex; justify-content: start">
								<span>电话：</span>
								<span>{{ row.networkWatcherContacts }}</span>
							</li>
						</ul>
					</template>
					<!-- <el-table-column min-width="130" :show-overflow-tooltip="true" align="center" prop="networkWatcherContacts" label="网络值班室电话" /> -->
				</el-table-column>
				<!-- 值班司机 -->
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" label="司机">
					<template #default="{ row }">
						<ul>
							<li style="display: flex; justify-content: start">
								<span>姓名：</span>
								<span>{{ row.driverName }}</span>
							</li>
							<li style="display: flex; justify-content: start">
								<span>电话：</span>
								<span>{{ row.driverContacts }}</span>
							</li>
						</ul>
					</template>
					<!-- <el-table-column min-width="120" :show-overflow-tooltip="true" align="center" prop="driverContacts" label="司机电话" /> -->
				</el-table-column>
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" label="操作">
					<template #default="{ row }">
						<el-button text type="primary" @click="editClick(row)">编辑</el-button>
						<el-button text type="danger" @click="deleteClick(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import {
	getLeaderClassApi,
	deleteLeaderClassApi,
	editLeaderClassApi,
	addLeaderClassApi,
	getEmployeeIdApi,
	getPostApi,
	addDutyPersonApi,
	getDutyPersonApi,
	deleteDutyPersonApi,
	updateDutyPersonApi,
} from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
/***** 查询 *****/
let searchObj: any = reactive({});
const transferVal1 = ref();
const transferVal2 = ref();
const searchClick = () => {
	// searchObj.CompanyName = transferVal1.value
	// searchObj.FormName = transferVal2.value
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

const resetClick = () => {
	// transferVal1.value =''
	// transferVal2.value=''
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};

/***** 新增 *****/
const showDialogVisible = ref(false);
const ruleForm = reactive({
	formName: '', //值班表名称
	companyName: '', //公司名称
	contactId: null, //联系人id
	contactPhoneNumber: '', //联系人电话号码
	remark: '', //备注
});
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

/***** 编辑 *****/
const saveId = ref(0);
const nodeClick = async (row: any) => {
	if (row.n_Id) {
		saveId.value = row.n_Id;
		ruleForm.formName = row.formName; //值班表名称
		ruleForm.companyName = row.companyName; //公司名称
		ruleForm.contactId = row.contactId; //联系人id
		ruleForm.contactPhoneNumber = row.contactPhoneNumber; //联系人电话号码
		ruleForm.remark = row.remark; //备注
	}
	showDialogVisible.value = true;
};

/*** 删除 */
const deleteHandle = async (val: String | Number) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: val };
			try {
				let res: any = await deleteLeaderClassApi(param);
				if (res.success) {
					getData();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

/***** 新增编辑表单校验和事件 *****/
const ruleFormRef = ref();
const rules = reactive({
	formName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	companyName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	contactId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	contactPhoneNumber: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
	],
});
const cancelUseClick = () => {
	showDialogVisible.value = false;
	saveId.value = 0;

	ruleForm.formName = ''; //值班表名称
	ruleForm.companyName = ''; //公司名称
	ruleForm.contactId = null; //联系人id
	ruleForm.contactPhoneNumber = ''; //联系人电话号码
	ruleForm.remark = ''; //备注

	ruleFormRef.value!.clearValidate();
};
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (saveId.value) {
				editLeaderClassApi({ ...ruleForm, n_id: saveId.value });
			} else {
				addLeaderClassApi(ruleForm);
			}
			setTimeout(() => {
				cancelUseClick();
				getData();
			}, 100);
		} else {
			console.log('error submit!', fields);
		}
	});
};

/***** 新增值班人员 *****/
const AddedDutyPersonnelInfo = async (row: any) => {
	watchkeeperRuleForm.formId = row.n_Id;
	options3.value = [];
	options2.value = [];
	const res = await getDutyPersonApi({ FormId: row.n_Id });
	tableData.value = res.data;
	showAddNodeDialogVisible.value = true;
};
// 删除值班人员
const deleteClick = async (row: any) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: row.n_Id };
			try {
				let res: any = await deleteDutyPersonApi(param);
				if (res.success) {
					const res = await getDutyPersonApi({ FormId: watchkeeperRuleForm.formId });
					tableData.value = res.data;
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};
// 新增值班人员选择事件
const options2: any = ref([]);
const options3: any = ref([]);
const selectLinkmanChange1 = async (val: number, str: any) => {
	let item: any = [];
	item = options1.value.filter((item: any) => {
		return item.value == val ? item : '';
	});
	// 领导
	if (str === 'leaderContacts') {
		options2.value = [];
		watchkeeperRuleForm.leaderPosId = '';
		const res = await getPostApi({ EmpId: val });
		if (res.data) {
			options2.value = res.data.map((item: any) => {
				return {
					value: item.sysPosId,
					label: item.sysPosName,
				};
			});
		} else {
			options2.value = [];
		}
	} else if (str === 'departHeaderContacts') {
		//部门负责人
		options3.value = [];
		watchkeeperRuleForm.departHeaderPosId = '';
		const res = await getPostApi({ EmpId: val });
		if (res.data) {
			options3.value = res.data.map((item: any) => {
				return {
					value: item.sysPosId,
					label: item.sysPosName,
				};
			});
		} else {
			options3.value = [];
		}
	}
	watchkeeperRuleForm[str] = item.length && item[0].phone;
};

// 编辑值班人员
const editId = ref(0);
const editClick = async (row: any) => {
	options2.value = [];
	options3.value = [];
	const res1 = await getPostApi({ EmpId: row.leaderId });
	options2.value = res1.data.map((item: any) => {
		return {
			value: item.sysPosId,
			label: item.sysPosName,
		};
	});
	//部门负责人
	const res2 = await getPostApi({ EmpId: row.departHeaderId });
	console.log(res2);
	options3.value = res2.data.map((item: any) => {
		return {
			value: item.sysPosId,
			label: item.sysPosName,
		};
	});

	editId.value = row.n_Id;

	watchkeeperRuleForm.dateOfDuty = row.dateOfDuty; //值班日期
	watchkeeperRuleForm.leaderId = row.leaderId; //值班领导id;请求员工下拉列表
	watchkeeperRuleForm.leaderPosId = row.leaderPosId; //领导岗位id;请求/SMS/DutyPserson/GetPosBydEmpId ;用leaderId作为参数
	watchkeeperRuleForm.leaderContacts = row.leaderContacts; //领导联系方式
	watchkeeperRuleForm.departHeaderId = row.departHeaderId; //部门负责人id;请求员工下拉列表
	watchkeeperRuleForm.departHeaderPosId = row.departHeaderPosId; //部门负责人岗位id，请求/SMS/DutyPserson/GetPosBydEmpId ;用DepartHeaderId作为参数
	watchkeeperRuleForm.departHeaderContacts = row.departHeaderContacts; //部门负责人联系方式
	watchkeeperRuleForm.watcherId = row.watcherId; //值班人id;请求员工下拉列表
	watchkeeperRuleForm.watcherContacts = row.watcherContacts; //值班室联系方式
	watchkeeperRuleForm.networkWatcherId = row.networkWatcherId; //网络值班人id;请求员工下拉列表
	watchkeeperRuleForm.networkWatcherContacts = row.networkWatcherContacts; //网络值班室联系方式
	watchkeeperRuleForm.driverId = row.driverId; //司机id;请求员工下拉列表
	watchkeeperRuleForm.driverContacts = row.driverContacts; //司机联系方式
};

// 新增值班人员
const addDutyPerson = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (editId.value) {
				console.log(editId.value);
				updateDutyPersonApi({ ...watchkeeperRuleForm, n_Id: editId.value }).then(() => {
					getDutyPersonApi({ FormId: watchkeeperRuleForm.formId }).then((res) => {
						tableData.value = res.data;
						resetDutyPerson();
					});
				});
			} else {
				addDutyPersonApi(watchkeeperRuleForm).then(() => {
					getDutyPersonApi({ FormId: watchkeeperRuleForm.formId }).then((res) => {
						tableData.value = res.data;
						resetDutyPerson();
					});
				});
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};
// 重置信息
const resetDutyPerson = () => {
	editId.value = 0;
	watchkeeperRuleForm.dateOfDuty = ''; //值班日期
	watchkeeperRuleForm.leaderId = ''; //值班领导id;请求员工下拉列表
	watchkeeperRuleForm.leaderPosId = ''; //领导岗位id;请求/SMS/DutyPserson/GetPosBydEmpId ;用leaderId作为参数
	watchkeeperRuleForm.leaderContacts = ''; //领导联系方式
	watchkeeperRuleForm.departHeaderId = ''; //部门负责人id;请求员工下拉列表
	watchkeeperRuleForm.departHeaderPosId = ''; //部门负责人岗位id，请求/SMS/DutyPserson/GetPosBydEmpId ;用DepartHeaderId作为参数
	watchkeeperRuleForm.departHeaderContacts = ''; //部门负责人联系方式
	watchkeeperRuleForm.watcherId = ''; //值班人id;请求员工下拉列表
	watchkeeperRuleForm.watcherContacts = ''; //值班室联系方式
	watchkeeperRuleForm.networkWatcherId = ''; //网络值班人id;请求员工下拉列表
	watchkeeperRuleForm.networkWatcherContacts = ''; //网络值班室联系方式
	watchkeeperRuleForm.driverId = ''; //司机id;请求员工下拉列表
	watchkeeperRuleForm.driverContacts = ''; //司机联系方式
};
//表单提交事件
const showAddNodeDialogVisible = ref(false);
const tableData: any = ref([]);
const cancelAddNodeClick = () => {
	// watchkeeperRuleFormRef.value?.resetFields()
	tableData.value = [];
	options2.value = [];
	options3.value = [];
	editId.value = 0;
	resetDutyPerson();
	// watchkeeperRuleFormRef.value!.resetFields()
	watchkeeperRuleFormRef.value!.clearValidate();
	showAddNodeDialogVisible.value = false;
};

// 表单校验
const watchkeeperRuleFormRef = ref();
const watchkeeperRules = reactive({
	dateOfDuty: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	leaderId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	leaderPosId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	leaderContacts: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
	],
	departHeaderId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	departHeaderPosId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	departHeaderContacts: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
	],
	watcherId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	watcherContacts: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
	],
	networkWatcherId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	networkWatcherContacts: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
	],
	driverId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	driverContacts: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' },
	],
});
const watchkeeperRuleForm: any = reactive({
	dateOfDuty: '', //值班日期
	leaderId: '', //值班领导id,请求员工下拉列表
	leaderPosId: '', //领导岗位id,请求/SMS/DutyPserson/GetPosBydEmpId ;用leaderId作为参数
	leaderContacts: '', //领导联系方式
	departHeaderId: '', //部门负责人id,请求员工下拉列表
	departHeaderPosId: '', //部门负责人岗位id，请求/SMS/DutyPserson/GetPosBydEmpId ;用DepartHeaderId作为参数
	departHeaderContacts: '', //部门负责人联系方式
	watcherId: '', //值班人id,请求员工下拉列表
	watcherContacts: '', //值班室联系方式
	networkWatcherId: '', //网络值班人id,请求员工下拉列表
	networkWatcherContacts: '', //网络值班室联系方式
	driverId: '', //司机id,请求员工下拉列表
	driverContacts: '', //司机联系方式
});

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'formName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'FormName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '值班表名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'companyName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'CompanyName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '公司名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'contactPhoneNumber', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'ContactPhoneNumber', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '联系人电话', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'empName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'ContactId', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '联系人', // placeholder数据
			defaultProp: options1.value, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};

/*** ================================= 导出数据函数操作 ================================= */
const excelRef: any = ref(null);
const handleExport = () => {
	if (excelRef.value) {
		if (excelRef.value.data.length !== 0) {
			let tableExcel: any = [];
			let tableArr = excelRef.value.data;
			tableArr.map((item: any) => {
				let tableObj: any = {};
				tableObj['值班表名称'] = item.formName ? item.formName : '-';
				tableObj['公司名称'] = item.companyName ? item.companyName : '-';
				tableObj['联系人'] = item.empName ? item.empName : '-';
				tableObj['联系人电话'] = item.contactPhoneNumber ? item.contactPhoneNumber : '-';
				tableObj['备注'] = item.remark ? item.remark : '-';

				tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
				tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
				tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
				tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
				tableExcel.push(tableObj);
			});
			exportToExcel(tableExcel, '领导干部带班表.xlsx');
		} else {
			ElMessage({
				type: 'error',
				message: '暂无数据导出',
			});
		}
	}
};

/*** 截取日期格式方法 */
const formatDate = (row: any, column: any) => {
	// 获取单元格数据
	let data = row[column.property];
	if (data == null) {
		return '-';
	}
	if (data === '1900-01-01 00:00:00') {
		return '-';
	}
	let dt = new Date(data);
	let month = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1;
	let date = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate();
	return dt.getFullYear() + '-' + month + '-' + date;
};

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getLeaderClassApi, {}, searchObj);

const options1: any = ref([]);
const selectLinkmanChange = (val: number) => {
	let item: any = [];
	item = options1.value.filter((item: any) => {
		return item.value == val ? item : '';
	});
	ruleForm.contactPhoneNumber = item.length && item[0].phone;
};
onMounted(async () => {
	const res = await getEmployeeIdApi();
	console.log(res);
	options1.value = res.data.map((item: any) => {
		return {
			value: item.id,
			label: item.name,
			phone: item.phone,
		};
	});

	await initInfoFun();
});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
